package com.sucisoft.base;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;

import androidx.annotation.Keep;
import androidx.multidex.MultiDex;

import com.taobao.sophix.PatchStatus;
import com.taobao.sophix.SophixApplication;
import com.taobao.sophix.SophixEntry;
import com.taobao.sophix.SophixManager;
import com.taobao.sophix.listener.PatchLoadStatusListener;

public class SophixStubApplication extends SophixApplication {
    private final String TAG = "SophixManager";

    // 此处SophixEntry应指定真正的Application，并且保证RealApplicationStub类名不被混淆。
    @Keep
    @SophixEntry(MyApplication.class)
    static class RealApplicationStub {
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
//         如果需要使用MultiDex，需要在此处调用。
        MultiDex.install(this);
        initSophix();
    }


    @Override
    public void onCreate() {
        super.onCreate();
        SophixManager.getInstance().queryAndLoadNewPatch();
    }


    private String rsaSecret() {
        return "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCt3Hku4s0Sg0UUOtSlMvTmSIXtcT4qTx++CpgvqFsV+HPQO0N3A3QwvAlf4dHfOCA5DpITlhToTjp8pJs3iVwgDyuC4gevdw5wLrMzXY0RgNptZ5QqVZGDD3qUL6FlRCluhHoosap5xfbeOIucfDIa7ENs+T45pk76m8NL04EyJx5bCrTId7uVxwidsLRJOQHjxlrq8HUp8mxNuy4Hb4DkS8DuygbpHQSBH+nTFrENaF3pDSdMej7IiYSPwVecm8rIlRZD8NyrEn6pL3Ur3zU3uA3990Dan/7nESKz9MzAN19EoGWLlIHTihPlanP6fPO1fPSNLnhojAh9gD/STtY1AgMBAAECggEAHnaB+TgeDH9ZrDi+p49tH6hXZwovhURF4IuErN0H0KquyC6KHKFLS3q2/cjYeA8ifjzSVYI3eZizYMGKvMlhjfB6hD1McW8f5YIZPgfHPujf3MmISX6it18P8EUEN3Ug+U9XBChVIW8RWVB5DdspAFSjX8WwJHPCZODD8FZHzdyI45eas+qBg6sQBRHYr5aeijvoCrJPGLsdj/dEImR5fUhGmshw1FpUpHF/GkjbwSniDsBo1mQbApzQkdl7KiKs/Bon+ek9Rupj6Sz8XPPCMhOWruwYWJ0XV3VJV7EvF32Tb9ih2E3eFhX1z382R29w69gVhjJycC2w6RyGClHyQQKBgQDTy+GooFFo/qZmj1tKh3Dl+py4p7sDwXy1y73M68B/LbS/PnojKS3HwGGkaaW+s9b9WcmTJS7gXqQvQ5OLdtV+eDPKNi+jTuQqDnuMSojM1GB9VdGd462SzOI+Zhsuwwfz0Kt8OJfaofyOIoXO+YHIbbFgqfCitb1JL8DNDS3lsQKBgQDSJb5/q/2gdXNwcwP6re7xJ42X3DQWcsbx8PjlYpB9NEPxPAx7VH87tcs75bU1odSLJiNfkRooSmBS/ItR2ihSRXmpmN0K5XOUN+BlajgKT9FFvPlxuVyWIt0fXGVtMfCY7EZhRDCzUovxI/W/uD4cBm364P2R3eBbf6dvOpKlxQKBgQCiI1OmXszT/xZuL1Lo9FTWiouNxUIi9u280rODe/tKoTfcrDyeTDjy0XEuh35ORqjQHPt2vSFsvKceU7JRMvDvt5+WLvM7Jvr+w0WLuceOXwtbB+bH43OOjXCp6krm+oFNArM1DrIZuqZ4PS+IqnPTdz4yTQad2VmF/JuxnmRDkQKBgQCVVQMBIMwTeUL2NpUuTulL7wp8TpupFBjxloaYIqmAf2KEi2JnRY1Adhgc0Ugq+3vZAdoDME6BMREwB4xNNxSOGhaxgRIaiyDNw8Mu7gMyuLOCth4gRVNY0R+HCJZ+uQ067jO5LMbatx8A1cftXFSuf5cpvzYRsLSc8KKftOS+7QKBgHb5phBgL6ORYsUoegP9iWwNoPz55ip/+AuLhzwPU6YGtkvq/YIEIbsyuihKhCGDAVgWNCr7Hjy2EPoWf3i0sektzIf/Qx57QARvkvOt2uVWnoIDrKJvyZBaU4BbqDvtdHwMxCep0n4U/oqc7bhBJnVZ5LdFg909ZuauTCrlxP3l";
    }

    private String appSecret() {
        return "44ee7187d32f6917fc09fd8dabfe33d7";
    }

    private String idSercert() {
        return "24664863-1";
    }

    /**
     * 返回当前程序版本名
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            //versioncode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {
            Log.e("VersionInfo", "Exception", e);
        }
        return versionName;
    }

    private void initSophix() {
        String appVersion = "0.0.0";
        try {
            appVersion = getAppVersionName(this);
        } catch (Exception e) {
        }
        SophixManager.getInstance().setContext(this)
                .setAppVersion(appVersion)
                .setAesKey(null)
                .setSecretMetaData(idSercert(), appSecret(), rsaSecret())
                .setEnableDebug(true)
                .setEnableFullLog()
                .setPatchLoadStatusStub(new PatchLoadStatusListener() {
                    @Override
                    public void onLoad(final int mode, final int code, final String info, final int handlePatchVersion) {
                        if (code == PatchStatus.CODE_LOAD_SUCCESS) {
                            Log.d(TAG, "sophix load patch success!");
                        } else if (code == PatchStatus.CODE_LOAD_RELAUNCH) {
                            // 如果需要在后台重启，建议此处用SharePreference保存状态。
                            Log.d(TAG, "sophix preload patch success. restart app to make effect.");
                            restartApp(SophixStubApplication.this);
                        } else {
                            Log.d(TAG, code + "  " + info);
                        }
                    }
                }).initialize();
    }

    public void restartApp(Context context) {
        restartAPP(context, 2000);
    }

    private void restartAPP(Context context, long Delayed) {
//        Intent intent1 = new Intent(context, KillSelfService.class);
//        intent1.putExtra("PackageName", context.getPackageName());
//        intent1.putExtra("Delayed", Delayed);
//        context.startService(intent1);
        SophixManager.getInstance().killProcessSafely();
    }
}